package net.cachapa.libra.widget;

import net.cachapa.libra.Preferences;
import net.cachapa.libra.R;
import net.cachapa.libra.data.Database;
import net.cachapa.libra.data.Value;
import net.cachapa.libra.util.MyDate;
import net.cachapa.libra.util.UnitManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.RemoteViews;

public class Widget extends AppWidgetProvider {
	private static final String WIDGET_TAPPED = "net.cachapa.libra.widget.WIDGET_TAPPED";

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		final int N = appWidgetIds.length;
		for (int i = 0; i < N; i++) {
			int appWidgetId = appWidgetIds[i];
			updateAppWidget(context, appWidgetManager, appWidgetId);
		}
	}
	
	@Override
	public void onDeleted(Context context, int[] appWidgetIds) {
	}
	
	@Override
	public void onEnabled(Context context) {
		PackageManager pm = context.getPackageManager();
		pm.setComponentEnabledSetting(new ComponentName("net.cachapa.libra", ".widget.Widget"),
				PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
	}
	
	@Override
	public void onDisabled(Context context) {
	}

	protected static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
		Database db = Database.getInstance(context);
		Value value = db.getLatestValue();
		if (value == null) {
			value = new Value(new MyDate(), 0, 0);
		}
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
		float goalWeight = prefs.getFloat(Preferences.GOAL_WEIGHT, 0);
		UnitManager um = UnitManager.getInstance(context);
		RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
		
		// Setting up the onClick method when the users taps the widget
		Intent intent = new Intent(context, Widget.class);
		intent.setAction(WIDGET_TAPPED);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
		views.setOnClickPendingIntent(R.id.WidgetLayout, pendingIntent);
		
		// Trend
		views.setTextViewText(R.id.TrendTextView, um.toWeightUnit(value.getTrend()));
		
		// Last update
		views.setTextViewText(R.id.WeightTextView, um.toWeightUnit(value.getWeight()));
		String lastUpdate;
		MyDate today = new MyDate();
		int elapsedDays = value.getDate().differenceInDays(today);
		switch (elapsedDays) {
		case 0:
			lastUpdate = context.getString(R.string.today);
			break;
		case 1:
			lastUpdate = context.getString(R.string.yesterday);
			break;
		default:
			lastUpdate = String.format(context.getString(R.string.n_days_ago), elapsedDays);
		}
		views.setTextViewText(R.id.DateTextView, lastUpdate);
		
		// To goal
		if (goalWeight == 0) {
			views.setViewVisibility(R.id.ToGoalLayout, View.GONE);
		}
		else {
			float diff = goalWeight - value.getTrend();
			String difference = "";
			if (diff > 0) {
				difference = "+";
			}
			difference += um.toWeightUnit(diff);
			views.setTextViewText(R.id.DifferenceWeightTextView, difference);
			Value goalValue = db.getGoalValue();
			String expected;
			if (goalValue == null || goalValue.getTrend() != goalWeight) {
				expected = context.getString(R.string.expected_unknown);
			}
			else {
				int daysToExpected = today.differenceInDays(goalValue.getDate());
				expected = String.format(context.getString(R.string.expected_in_n_days), daysToExpected);
			}
			views.setTextViewText(R.id.ExpectedDateTextView, expected);
		}

		// Tell the widget manager
		appWidgetManager.updateAppWidget(appWidgetId, views);
	}
	
	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		if (action.equals(Database.DATABASE_CHANGED) || action.equals(Intent.ACTION_DATE_CHANGED)) {
			AppWidgetManager gm = AppWidgetManager.getInstance(context);
            int[] ids = gm.getAppWidgetIds(new ComponentName(context, Widget.class));
            for (int id : ids) {
            	Widget.updateAppWidget(context, gm, id);
			}
		}
		else if (action.equals(WIDGET_TAPPED)) {
			Value value = Database.getInstance(context).getLatestValue();
			// Check if the most recent insertion was today
			Intent activityIntent;
			if (value == null || value.getDate().equals(new MyDate())) {
				activityIntent = new Intent(context, net.cachapa.libra.Main.class);
			}
			else {
				activityIntent = new Intent(context, net.cachapa.libra.InsertValue.class);
			}
			activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(activityIntent);
		}
		else {
			super.onReceive(context, intent);
		}
	}
}
